<template>
  <div class="app-container">
    <div id="message-box" class="message-list">
      <el-button v-if="!showHistory" id="btn-more" type="info" round style="align-self: center;padding: 5px" @click="showMore">查看历史</el-button>
      <div v-for="(item, index) in history" :id="'dialog' + index" :key="index" class="message-item" :style="{'align-self': (item.sender.id !== id ? 'flex-start':'flex-end') }">
        <el-avatar v-if="item.sender.id !== id" :size="70" :src="item.sender.avatar" />
        <div class="message-item-content">
          <div class="message-item-user" :style="{'align-self': (item.sender.id !== id ? 'flex-start':'flex-end') }">
            {{ item.sender.name }}
            <span>{{ item.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </div>
          <div :class="'dialog-box-' + (item.sender.id !== id ? 'left':'right')">
            <div v-html="item.content" />
            <div v-if="item.type !== 'dialog'" class="btn-bar">
              <el-button type="primary">同意</el-button>
              <el-button type="danger">拒绝</el-button>
            </div>
          </div>
        </div>
        <el-avatar v-if="item.sender.id === id" :size="70" :src="item.sender.avatar" />
      </div>
    </div>
    <el-form class="input-box">
      <el-form-item>
        <el-input v-model="form.content" :autosize="{ minRows: 8, maxRows: 8}" class="textarea" type="textarea" />
      </el-form-item>
      <el-form-item class="btn-bar">
        <el-button type="primary" @click="sendMsg">发送</el-button>
        <el-button>撤销</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import { getHistory, sendP2PMessage, getGroupInfoByName } from '@/api/inform'
// eslint-disable-next-line no-unused-vars
import { parseTime } from '@/utils'
import { Loading } from 'element-ui'
var loadingInstance = null
export default {
  name: 'P2P',
  data() {
    return {
      groupName: this.$route.params.name,
      groupId: -1,
      showHistory: false,
      scrollListener: null,
      listQuery: {
        page: 0,
        limit: 5,
        groupName: this.$route.params.name
      },
      id: this.$store.getters.id,
      form: {
        message: 'new dialog',
        content: '',
        senderId: this.$store.getters.id,
        type: 'dialog',
        groupName: this.$route.params.name,
        senderName: this.$store.getters.name
      },
      loadingOptions: {
        target: '.app-container',
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      },
      history: []
    }
  },
  computed: {
    listenWebsocket() {
      return this.$store.state.websocket.message
    }
  },
  watch: {
    listenWebsocket: function(newstr) {
      const form = JSON.parse(newstr)
      if (form.message === 'new dialog') {
        const msg = Object.assign({}, JSON.parse(form.items))
        console.log(msg)
        msg.createTime = new Date(msg.createTime).getTime()
        this.history.push(msg)
        if (msg.sender.id === this.id) {
          const msgBox = document.getElementById('message-box')
          this.form.content = ''
          setTimeout(
            () => {
              msgBox.scrollTo({
                top: msgBox.scrollHeight,
                behavior: 'smooth'
              })
            }, 200
          )
        } else {
          getHistory(this.listQuery)
          this.$notify({
            title: msg.sender.name,
            message: (msg.content.length > 25 ? msg.content.substring(0, 25) + '...' : msg.content),
            type: 'success',
            duration: 4000
          })
        }
      }
    }
  },
  created() {
    console.log(this.groupName)
  },
  mounted() {
    getGroupInfoByName(this.groupName).then(
      res => {
        this.groupId = res.data.items.id
        this.getHistory()
      }
    )
  },
  methods: {
    getElementTop(element) {
      var actualTop = element.offsetTop
      var current = element.offsetParent
      while (current !== null) {
        actualTop += current.offsetTop
        current = current.offsetParent
      }
      return actualTop
    },
    scrollTo(id, offset) {
      const element = document.getElementById(id)
      var actualTop = element.offsetTop
      var current = element.offsetParent
      var elementScrollTop = null
      while (current !== null) {
        actualTop += current.offsetTop
        current = current.offsetParent
      }
      if (document.compatMode === 'BackCompat') {
        elementScrollTop = document.body.scrollTop
      } else {
        elementScrollTop = document.documentElement.scrollTop
      }
      document.getElementById('message-box').scrollTo(0, actualTop - elementScrollTop + offset)
    },
    showMore() {
      this.showHistory = true
      this.getHistory()
    },
    getHistory() {
      const messageBox = document.getElementById('message-box')
      const self = this
      this.listQuery.page++
      loadingInstance = Loading.service(this.loadingOptions)
      if (self.listQuery.page <= 2 && self.showHistory) {
        self.scrollListener = () => {
          const messageBox = document.getElementById('message-box')
          if (messageBox.scrollTop <= 0) {
            self.getHistory()
          }
        }
        messageBox.addEventListener('scroll', self.scrollListener)
      }
      getHistory(this.listQuery).then(
        res => {
          for (const i in res.data.items) {
            this.history.unshift(res.data.items[i])
            this.history[0].createTime = new Date(this.history[0].createTime).getTime()
          }
          setTimeout(
            () => {
              if (res.data.items.length > 0) {
                console.log(res.data.items.length)
                if (this.listQuery.page > 1 && document.getElementById('dialog' + (res.data.items.length - 1)) !== null) {
                  this.scrollTo('dialog' + (res.data.items.length - 1), 0)
                }
              } else {
                if (messageBox.scrollTop <= 0) {
                  this.$notify({
                    title: '已到顶部',
                    message: '',
                    type: 'info',
                    duration: 1000
                  })
                }
              }
              loadingInstance.close()
            },
            300
          )
        }
      )
    },
    sendMsg() {
      var msg = Object.assign({}, this.form)
      this.$store.dispatch('websocket/WEBSOCKET_SEND', JSON.stringify(msg))
    },
    setTagsViewTitle(name) {
      this.$route.meta.title = name + '-通知'
      const currentView = this.$store.getters.visitedViews[this.$store.getters.visitedViews.findIndex(
        (item) => item.path === this.$route.path
      )]
      if (currentView != null) {
        currentView.title = name + '-通知'
      }
    },
    setPageTitle(name) {
      document.title = `${name}` + '-通知'
    }
  }
}
</script>

<style scoped lang="scss">
  $triangle-size: 10px;
  $triangle-width: 4px;
  .app-container{
    height: calc(100vh - 90px);
    padding: 0 5px;
    display: flex;
    flex-direction: column;
  }
  .dialog-box-left {
    left: 10px;
    min-height: 50px;
    max-width: 500px;
    position: relative;
    background: #88b7d5;
    border: 4px solid #c2e1f5;
    border-radius: 20px;
    padding: 10px 15px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .btn-bar{
      margin-top: 20px;
      align-self: flex-end;
    }
  }
  .dialog-box-left:after, .dialog-box-left:before {
    right: 100%;
    top: 20px;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .dialog-box-left:after {
    border-color: rgba(136, 183, 213, 0);
    border-right-color: #88b7d5;
    border-width:$triangle-size - $triangle-width;
    margin-top:-$triangle-size + $triangle-width;
  }
  .dialog-box-left:before {
    border-color: rgba(194, 225, 245, 0);
    border-right-color: #c2e1f5;
    border-width: $triangle-size;
    margin-top: -$triangle-size;
  }
  .dialog-box-right {
    min-height: 50px;
    max-width: 500px;
    position: relative;
    background: #45eab3;
    border: 4px solid #7dfcd6;
    border-radius: 20px;
    padding: 10px 15px;
    margin-right: 10px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    .btn-bar{
      margin-top: 20px;
      align-self: flex-end;
    }
  }
  .dialog-box-right:after, .dialog-box-right:before {
    left: 100%;
    top: 20px;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }

  .dialog-box-right:after {
    border-color: rgba(136, 183, 213, 0);
    border-left-color:  #45eab3;
    border-width:$triangle-size - $triangle-width;
    margin-top:-$triangle-size + $triangle-width;
  }
  .dialog-box-right:before {
    border-color: rgba(194, 225, 245, 0);
    border-left-color: #7dfcd6;
    border-width: $triangle-size;
    margin-top: -$triangle-size;
  }
  .message-list{
    display: flex;
    flex-direction: column;
    height: 70vh;
    overflow: auto;
    padding: 20px;
    min-height: 80px;
    top: 40px;
    box-shadow: 0 3px 6px #888888;
    .message-item{
      display: flex;
      flex-direction: row;
      margin-top: 20px;
      .message-item-content{
        display: flex;
        flex-direction: column;
        .message-item-user{

        }
      }
    }
  }
  .input-box{
    display: flex;
    flex-direction: column;
    margin-top: 5px;
    .textarea{
      font-size: 18px;
    }
    .btn-bar{
      position: absolute;
      bottom: 20px;
      right: 30px;
      align-self: flex-end;
    }
  }
</style>
